/**
 * @version 1.0
 * @author Ha Giang
 * @date
 */
package DiscoveryFunction;

import Configuration.Utils;
import java.util.*;
import java.util.concurrent.*;

public class Directory {

    //hash table of services
    private ConcurrentHashMap<String, ServiceInfo> services = new ConcurrentHashMap();
    private long time_2_clean = Utils.ONE_HOUR;

    /**
     * Get the list of available services
     *
     * @return The hash table contains services
     */
    public ConcurrentHashMap<String, ServiceInfo> getServices() {
        return services;
    }

    /**
     * List all services to console
     */
    public void listAllServices() {
        System.out.println("Directory: Listing services! # of services: " + services.size());
        Enumeration e = services.keys();

        //iterate through Hashtable keys Enumeration
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            System.out.println(o + "-->" + services.get(o));
        }
    }

    /**
     * Start 2 threads to process messages from clients and services
     */
    public void start() {
        new ServicesProcessorThread(this).start();
        new ClientsProcessorThread(this).start();
    }

    /**
     * Auto flush expired services TODO: delegate this task to a DBMS (ex: MSSQL
     * Server)
     */
    public void startAutoClean() {//in millisecond
        long delay = 1000;   // delay for 1 sec.
        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                // Task here ...
                //clean the hash table
                //list all services 
                Enumeration e = services.keys();

                //iterate through Hashtable keys Enumeration
                while (e.hasMoreElements()) {
                    Object UUID = e.nextElement();
                    ServiceInfo si = services.get(UUID);
                    if (si.getExpire() > time_2_clean) {
                        si.setExpire(si.getExpire() - time_2_clean);
                    }
                }
            }
        }, delay, time_2_clean);
    }
}
